package com.ruoyi.web.controller.pneumatic;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.entity.FileDataEntity;
import com.ruoyi.entity.SubjectEntity;
import com.ruoyi.entity.ProjectEntity;
import com.ruoyi.entity.FileEntity;
import com.ruoyi.entity.SettingEntity;
import com.ruoyi.web.service.FileService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.page.TableDataInfo;

import java.io.IOException;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.ArrayList;
import java.util.stream.Collectors;
import java.util.Collection;
import com.ruoyi.web.service.PneumaticService;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.ruoyi.common.exception.file.FileNameExistsException;


@Api(tags = "气动热数据库系统接口数据")
@RestController
@RequestMapping("/pneumatic")
public class pneumaticController extends BaseController {
    @Autowired
    private FileService fileService;
    @Autowired
    private PneumaticService taskService;

    @GetMapping("/subjectList")
    public TableDataInfo getProductsInfo(SubjectEntity reqDTO) throws IOException {
        startPage();
        List<SubjectEntity> list = taskService.getSubjectList(reqDTO);
        return getDataTable(list);
    }
    @DeleteMapping("/removeSubject/{subjectIds}")
    public AjaxResult remove(@PathVariable String[] subjectIds) throws IOException {
        return toAjax(taskService.deleteSubjectByIds(subjectIds));
    }

    @PostMapping("/addSubject")
    public AjaxResult add(@Validated @RequestBody SubjectEntity task) throws IOException
    {
        return toAjax(taskService.insertSubject(task));
    }
    @PutMapping("/updateSubject")
    public AjaxResult edit(@Validated @RequestBody SubjectEntity task) throws IOException {
        return toAjax(taskService.updateSubject(task));
    }


    @GetMapping("/projectList")
    public TableDataInfo getProjectsInfo(ProjectEntity reqDTO) throws IOException {
        startPage();
        List<ProjectEntity> list = taskService.getProjectList(reqDTO);
        return getDataTable(list);
    }
    @PostMapping("/addProject")
    public AjaxResult addProject(@Validated @RequestBody ProjectEntity task) throws IOException
    {
        return toAjax(taskService.insertProject(task));
    }
    @DeleteMapping("/removeProject/{projectIds}")
    public AjaxResult removeProject(@PathVariable String[] projectIds) throws IOException {
        return toAjax(taskService.deleteProjectByIds(projectIds));
    }
    @PutMapping("/updateProject")
    public AjaxResult updateProject(@Validated @RequestBody ProjectEntity project) throws IOException {
        return toAjax(taskService.updateProject(project));
    }
    @GetMapping("/fileList")
    public TableDataInfo getFilesInfo(FileEntity reqDTO) throws IOException {
        startPage();
        List<FileEntity> list = taskService.getFileList(reqDTO);
        return getDataTable(list);
    }

    @PostMapping("/file/upload")
    public AjaxResult uploadFile(
            @RequestParam("file") MultipartFile[] file,
            @RequestParam("id") String id,
            @RequestParam("workType") String workType,
            @RequestParam("fileType") String fileType,
            @RequestParam("projectId") Integer projectId,
            @RequestParam("timeStamp") BigInteger timeStamp,
            @RequestParam(value = "fileData", required = false, defaultValue = "[]") String fileData,
            @RequestParam(value = "resultData", required = false, defaultValue = "[]") String resultData
            ) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            List<FileDataEntity> records = objectMapper.readValue(fileData, new TypeReference<List<FileDataEntity>>(){});
            List<FileDataEntity> resultRecords = objectMapper.readValue(resultData, new TypeReference<List<FileDataEntity>>(){});
            if (fileService.savePneumaticFileService(file, id, workType, fileType, projectId, timeStamp, records, resultRecords)==1) {
                return AjaxResult.success();
            } else {
                String imageName = "";
                for(MultipartFile fileDataName: file){
                    imageName=fileDataName.getOriginalFilename();
                }
                return AjaxResult.error(imageName + "文件已存在,请修改后上传");
            }
//            return toAjax(fileService.savePneumaticFileService(file, id, workType, fileType, projectId, timeStamp, records, resultRecords));
        } catch (FileNameExistsException ex) {
            System.out.println("Caught FileNameExistsException: " + ex.getMessage());
            return AjaxResult.error("File with name already exists: " + ex.getMessage());
        }  catch (Exception e) {
            System.out.println(1222);
        }
        return null;
    }
    @GetMapping("/getFileData")
    public TableDataInfo getFileData(FileDataEntity reqDTO) throws IOException {
        List<FileDataEntity> list = taskService.getFileData(reqDTO);
        return getDataTable(list);
    }
    @GetMapping("/getFileResultData")
    public TableDataInfo getFileResultData(FileDataEntity reqDTO) throws IOException {
        List<FileDataEntity> list = taskService.getFileResultData(reqDTO);
        return getDataTable(list);
    }
    @PostMapping("/file/download")
    public Map<String, String> downloadFile(@RequestBody Map<String, String> request) {
        try {
            Map<String, String> result = new HashMap<>();
            String url = taskService.getDownloadUrl(request.get("workType"), request.get("fileName"));
            result.put("url", url);
            return result;
        } catch (Exception e) {
        }
        return null;
    }

    @DeleteMapping("/file/removeFile")
    public AjaxResult removeFile(@RequestBody Map<String, Object> request) throws IOException {
        List<String> fileIds = (List<String>) request.get("fileIds");
        List<String> fileNames = (List<String>) request.get("fileNames");
        String directory = (String) request.get("directory");
        return toAjax(taskService.deleteFileByIds(fileIds, fileNames, directory));
    }
    @PostMapping("/globalSearch")
    public TableDataInfo globalSearch(@RequestParam("fileType") String fileType, @RequestBody Map<String, List<FileDataEntity>> reqDTO) throws IOException {
        List<FileDataEntity> pneumaticList = reqDTO.get("pneumaticForm");
        List<FileDataEntity> list = taskService.globalSearch(pneumaticList);

        Set<String> requiredKeys = pneumaticList.stream()
                .map(FileDataEntity::getPneumaticKey)
                .collect(Collectors.toSet());

        // 获取到fileData按照file_id和row_index进行分组,确保是在同一行的同一个文件里面
        Map<String,  Map<Integer, List<FileDataEntity>>> groupedByFileId = list.stream()
                .collect(Collectors.groupingBy(
                        FileDataEntity::getFileId,
                        Collectors.groupingBy(FileDataEntity::getRowIndex)
                ));

        List<FileDataEntity> filteredData = groupedByFileId.values().stream()
                .flatMap(rowIndexMap -> rowIndexMap.values().stream())
                .filter(entities -> {
                    // 确保每个 rowIndex 包含 pneumaticForm 中的所有键值对
                    Set<String> keysInEntities = entities.stream()
                            .map(FileDataEntity::getPneumaticKey)
                            .collect(Collectors.toSet());

                    // 确保所有需要的键值对都存在
                    return keysInEntities.containsAll(requiredKeys);
                })
                .flatMap(Collection::stream)
                .collect(Collectors.toList());
        System.out.println(filteredData);
        Set<String> fileIds = filteredData.stream()
                .map(FileDataEntity::getFileId)
                .collect(Collectors.toSet());
        System.out.println(fileIds);
        if (!fileIds.isEmpty()) {
            startPage();
            List<FileEntity> fileList = taskService.getFileListByIds(fileIds, fileType);
            return getDataTable(fileList);
        } else {
//            String fileType = reqDTO.get("fileType").toString();
            List<FileEntity> emptyList = new ArrayList<>();
            return getDataTable(emptyList);
        }
    }
    @PostMapping("/updateUserSubject")
    public List<SubjectEntity> updateUserSubject(@RequestBody Map<String, String> requestBody) throws IOException {
        String userId = requestBody.get("userId");
        String subjectIds = requestBody.get("subjectIds");
        taskService.updateUserSubject(userId, subjectIds);
        List<SubjectEntity> list = taskService.authSubjectList(userId);
        return list;
    }
    @GetMapping("/authSubjectList")
    public TableDataInfo authSubjectList(@RequestParam("userId") String userId) throws IOException {
        startPage();
        List<SubjectEntity> list = taskService.authSubjectList(userId);
        return getDataTable(list);
    }

    @GetMapping("/settingList")
    public TableDataInfo getSettingsInfo(SettingEntity reqDTO) throws IOException {
        startPage();
        List<SettingEntity> list = taskService.getSettingsInfo(reqDTO);
        return getDataTable(list);
    }
    @PostMapping("/addSetting")
    public AjaxResult addSetting(
            @RequestParam MultipartFile file,
            @RequestParam String loginTitle,
            @RequestParam Integer isActive
    )  throws IOException {
        String fileName=file.getOriginalFilename();
        taskService.addSetting(file, loginTitle, isActive);
        return new AjaxResult(HttpStatus.SUCCESS,"上传成功",null);
    }
    @PostMapping("/setting/activate")
    public AjaxResult activate(@RequestBody Map<String, Integer> request) {
        Integer id = request.get("id");
        taskService.activate(id);
        return new AjaxResult(HttpStatus.SUCCESS,"操作成功",null);
    }
    @PostMapping("/removeSetting")
    public AjaxResult removeSetting(@RequestBody SettingEntity reqDTO) throws IOException {
        Integer id = reqDTO.getId();
        String fileName = reqDTO.getLoginImage();
        return toAjax(taskService.removeSetting(id, fileName));
    }
    @PostMapping("/getSetting")
    public AjaxResult getSetting() throws IOException {
        SettingEntity detail = new SettingEntity();
        detail = taskService.getSetting();
        return new AjaxResult(HttpStatus.SUCCESS,"操作成功", detail);
    }
}
